package com.example.demo.utils;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TCPUtil {

    public static List<Socket> onlineSockets = new ArrayList<>();

    public void send() throws IOException {
        Socket socket = new Socket("localhost", 8888);//创建socke客户端

        //线程池管理
        int cpus = Runtime.getRuntime().availableProcessors();
        ThreadPoolExecutor pool = new ThreadPoolExecutor(cpus * 2, cpus * 2, 0, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(8), Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        //创建线程接受服务端消息
        pool.execute(new TCPClientReaderThread(socket));

        OutputStream os = socket.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os);//包装输出流
        Scanner sc = new Scanner(System.in);//创建用户输入器
        while (true) {
            String msg = sc.nextLine();//用户输入
            if (msg.equals("exit")) {
                System.out.println("退出");
                break;
            }
            dos.writeUTF(msg);//发送
            dos.flush();
        }
        dos.close();
        socket.close();
    }

    public void receive() throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);//创建socke服务端
        while (true) {
            Socket socket = serverSocket.accept();//接受客户端请求
            onlineSockets.add(socket);//上线加入集合
            System.out.println(socket.getRemoteSocketAddress() + "上线了");
            new TCPServerReaderThread(socket).start();//分发给子线程处理
        }

    }
}
